﻿/// jQuery plugin to add support for SwfUpload
/// (c) 2008 Steven Sanderson

(function($) {
    $.fn.makeAsyncUploader = function(options) {
        return this.each(function() {
            // Put in place a new container with a unique ID
            var id = $(this).attr("id");
            var container = $("<span class='asyncUploader' style='display:block'/>");
            container.append($("<div class='ProgressBar'> <div>&nbsp;</div> </div>"));
            container.append($("<span id='" + id + "_completedMessage'/>"));
            container.append($("<span id='" + id + "_uploading'> <input type='button' value='Cancel'/></span>"));
            container.append($("<span id='" + id + "_swf'/>"));
            container.append($("<input type='hidden' name='" + id + "_filename'/>"));
            container.append($("<input type='hidden' name='" + id + "_guid'/>"));

            var listFiles = $("<div id='" + id + "_listFile' />");
            listFiles.append($("<ul>"));
            var $this = $(this);

            var value = $(this).val();
            if (typeof(value) != "undefined" && value.trim().length > 0) {
                value = value.trim();
                var ids = value.split(',');
                if (ids.length > 0) {
                    var ul = listFiles.find("ul");
                    for (var i = 0; i < ids.length; i++) {
                        var li = $("<li fileId=\"" + ids[i] + "\"/>");

                        var fileName = ids[i];
                        $.ajax({
                            url: "/upload/get/" + ids[i],
                            async: false,
                            success: function(data) {
                                fileName = data;
                            }
                        });


                        var a_File = $("<a href=\"/Upload/DownloadFile/" + ids[i] + "\" class=\"filename\">" + fileName + "</a>");

                        var a_del = $("<a href=\"javascript:void(0)\" class=\"del-file\" fileId=\"" + ids[i] + "\"> <i class=\"glyphicon glyphicon-trash\"></i></a>");
                        a_del.click(function() {
                            if (confirm("are you sure want to delete")) {
                                var fileId = $(this).attr("fileId");
                                var f_value = $($this).val();
                                if (typeof(f_value) != "undefined" && f_value.trim().length > 0) {
                                    f_value = f_value.trim();
                                    var f_ids = f_value.split(',');
                                    if (f_ids.length > 0) {
                                        f_ids.remove(fileId);
                                        $("li[fileId=" + fileId + "]").remove();
                                        $($this).val(f_ids.toString());
                                    }
                                }
                            }
                            ;
                        });

                        $(li).append(a_File);
                        $(li).append(a_del);

                        $(ul).append(li);
                    }
                }
            }

            if (listFiles.find("li").length == 0) {
                listFiles.hide();
            }

            $(this).before(listFiles);
            $(this).before(container);
            $("div.ProgressBar", container).hide();
            $("span[id$=_uploading]", container).hide();


            // Instantiate the uploader SWF
            var swfu;
            var width = 109, height = 22;
            if (options) {
                width = options.width || width;
                height = options.height || height;
            }
            var defaults = {
                flash_url: "swfupload.swf",
                upload_url: "/Home/AsyncUpload",
                file_size_limit: "3 MB",
                file_types: "*.*",
                file_types_description: "All Files",
                debug: false,

                button_image_url: "blankButton.png",
                button_width: width,
                button_height: height,
                button_placeholder_id: id + "_swf",
                button_text: "<font face='Arial' size='13pt'>Choose file</font>",
                button_text_left_padding: (width - 70) / 2,
                button_text_top_padding: 1,

                // Called when the user chooses a new file from the file browser prompt (begins the upload)
                file_queued_handler: function(file) { swfu.startUpload(); },

                // Called when a file doesn't even begin to upload, because of some error
                file_queue_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                // Called when an error occurs during upload
                upload_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                // Called when upload is beginning (switches controls to uploading state)
                upload_start_handler: function() {
                    swfu.setButtonDimensions(0, height);
                    $("input[name$=_filename]", container).val("");
                    $("input[name$=_guid]", container).val("");
                    $("div.ProgressBar div", container).css("width", "0px");
                    $("div.ProgressBar", container).show();
                    $("span[id$=_uploading]", container).show();
                    $("span[id$=_completedMessage]", container).html("").hide();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).attr("disabled", "disabled");
                },

                // Called when upload completed successfully (puts success details into hidden fields)
                upload_success_handler: function(file, response) {
                    $("input[name$=_filename]", container).val(file.name);
                    $("input[name$=_guid]", container).val(response);
                    //$("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                    //            .replace("{0}", file.name)
                    //            .replace("{1}", Math.round(file.size / 1024))
                    //        );

                    var u_li = $("<li fileId=\"" + response + "\"/>");

                    var u_File = $("<a href=\"/Upload/DownloadFile/" + response + "\" class=\"filename\">" + file.name + "</a>");

                    var u_del = $("<a href=\"javascript:void(0)\" class=\"del-file\" fileId=\"" + response + "\"> <i class=\"glyphicon glyphicon-trash\"></i></a>");
                    u_del.click(function() {
                        if (confirm("are you sure want to delete")) {
                            var fileId = $(this).attr("fileId");
                            var f_value = $($this).val();
                            if (typeof(f_value) != "undefined" && f_value.trim().length > 0) {
                                f_value = f_value.trim();
                                var f_ids = f_value.split(',');
                                if (f_ids.length > 0) {
                                    f_ids.remove(fileId);
                                    $("li[fileId=" + fileId + "]").remove();
                                    $($this).val(f_ids.toString());
                                }
                            }
                        }
                        ;
                    });

                    $(u_li).append(u_File);
                    $(u_li).append(u_del);
                    $($this).val($($this).val() + ($($this).val().length > 0 ? "," : "")+ response);
                    $('div[id$=_listFile] ul').append(u_li);
                    $('div[id$=_listFile]').show();
                },

                // Called when upload is finished (either success or failure - reverts controls to non-uploading state)
                upload_complete_handler: function() {
                    var clearup = function() {
                        $("div.ProgressBar", container).hide();
                        //$("span[id$=_completedMessage]", container).show();
                        $("span[id$=_uploading]", container).hide();
                        swfu.setButtonDimensions(width, height);
                    };
                    if ($("input[name$=_filename]", container).val() != "") // Success
                        $("div.ProgressBar div", container).animate({ width: "100%" }, { duration: "fast", queue: false, complete: clearup });
                    else // Fail
                        clearup();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).removeAttr("disabled");
                },

                // Called periodically during upload (moves the progess bar along)
                upload_progress_handler: function(file, bytes, total) {
                    var percent = 100 * bytes / total;
                    $("div.ProgressBar div", container).animate({ width: percent + "%" }, { duration: 500, queue: false });
                }
            };
            swfu = new SWFUpload($.extend(defaults, options || { }));

            // Called when user clicks "cancel" (forces the upload to end, and eliminates progress bar immediately)
            $("span[id$=_uploading] input[type='button']", container).click(function() {
                swfu.cancelUpload(null, false);
            });

            // Give the effect of preserving state, if requested
            if (options.existingFilename || "" != "") {
                $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                    .replace("{0}", options.existingFilename)
                    .replace("{1}", options.existingFileSize ? Math.round(options.existingFileSize / 1024) : "?")
                ).show();
                $("input[name$=_filename]", container).val(options.existingFilename);
            }
            if (options.existingGuid || "" != "")
                $("input[name$=_guid]", container).val(options.existingGuid);
        });
    };
})(jQuery);

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};